package xin.marcher.module.rights.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.rights.domain.bo.EshopUserDetails;
import xin.marcher.module.rights.domain.dto.PermissionDTO;
import xin.marcher.module.rights.domain.dto.RolePermissionRelationDTO;
import xin.marcher.module.rights.domain.dto.UserDTO;
import xin.marcher.module.rights.domain.dto.UserRoleRelationDTO;
import xin.marcher.module.rights.repository.RightsRepository;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class EshopUserDetailsServcieImpl implements UserDetailsService {

    @Autowired
    private RightsRepository rightsRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        EshopUserDetails eshopUserDetails = new EshopUserDetails();

        // 查询用户
        UserDTO userDTO = rightsRepository.queryUserByUsername(username);
        if (Objects.isNull(userDTO)) {
            throw new BaseBizException("用户不存在");
        }
        eshopUserDetails.setUserId(userDTO.getId());
        eshopUserDetails.setUsername(userDTO.getUsername());
        eshopUserDetails.setPassword(userDTO.getPassword());

        // 查询用户的角色
        List<UserRoleRelationDTO> userRoleRelationDTOList = rightsRepository.queryUserRoleRelationByUserId(userDTO.getId());
        if (CollectionUtils.isEmpty(userRoleRelationDTOList)) {
            return eshopUserDetails;
        }

        // 查询角色的权限
        List<Long> roleIds = userRoleRelationDTOList.stream().map(UserRoleRelationDTO::getRoleId).collect(Collectors.toList());
        List<RolePermissionRelationDTO> rolePermissionRelationDTOList = rightsRepository.queryRolePermissionRelation(roleIds);
        if (CollectionUtils.isEmpty(rolePermissionRelationDTOList)) {
            return eshopUserDetails;
        }

        // 查询权限信息
        List<Long> permissionIds = rolePermissionRelationDTOList.stream().map(RolePermissionRelationDTO::getPermissionId).collect(Collectors.toList());
        List<PermissionDTO> permissionDTOS = rightsRepository.queryPermissionByIds(permissionIds);
        if (CollectionUtils.isEmpty(permissionDTOS)) {
            return eshopUserDetails;
        }

        // 当前这个用户具有的所有权限
        Set<String> permissionCodeSet = permissionDTOS.stream().map(PermissionDTO::getPermissionCode).collect(Collectors.toSet());
        eshopUserDetails.setPermissionCodes(permissionCodeSet);
        return eshopUserDetails;
    }
}
